package com.bw.home.viewmodel

import androidx.lifecycle.viewModelScope
import com.bw.home.intent.SimpleTypeIntent
import com.bw.home.service.SimpleTypeService
import com.bw.home.state.SimpleTypeState
import com.bw.lib_mvi.viewmodel.BaseViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch

class SimpleTypeViewModel : BaseViewModel<SimpleTypeIntent>() {
    private val service: SimpleTypeService by lazy { SimpleTypeService() }

    //可改变状态流
    private val _state = MutableStateFlow<SimpleTypeState>(SimpleTypeState.init)

    //可观察
    val state: StateFlow<SimpleTypeState>
        get() = _state

    override fun handlerIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect {
                when (it) {

                    is SimpleTypeIntent.getSimpleType -> {
                        doSimpleType(it)
                    }

                    else -> {}
                }
            }
        }
    }

    private fun doSimpleType(it: SimpleTypeIntent.getSimpleType) {
        viewModelScope.launch(Dispatchers.IO) {
            val data = service.getSimpleType()
            if (data.code == 0) {
                _state.value = SimpleTypeState.SimpleTypeSuccess(data.data)
            } else {
                _state.value = SimpleTypeState.Failed
            }
        }
    }
}